<template>
  <basic-container>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="first">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
          <el-row :gutter="15">
            <el-col :span="12">
              <el-form-item label="登录账号" prop="account">{{ruleForm.account}}</el-form-item>
              <el-form-item label="姓名" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入姓名" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                <el-input v-model="ruleForm.mobile" placeholder="请输入手机号" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="身份证号" prop="cardNo">
                <el-input v-model="ruleForm.cardNo" placeholder="请输入身份证号" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm.email" placeholder="请输入邮箱" autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button
                        style="padding:10px 30px"
                        type="primary"
                        icon="el-icon-circle-check"
                        @click="submitForm()">保存
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="头像" prop="logo">
                <el-upload
                        ref="upload"
                        class="avatar-uploader"
                        action="#"
                        accept="image/jpg,image/jpeg,image/bmp,image/png"
                        :show-file-list="false"
                        :before-upload="beforeUpload"
                        :http-request="uploadImage">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  <div slot="tip" style="color:#999">支持jpg、jpeg、png、bmp格式，且照片小于5M</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="安全设置" name="second">
        <el-card>
          <div slot="header">
            <h3 class="el-card__title">
              登录密码
              <small style="color:#999">密码为6-20位，必须含字母+数字</small>
            </h3>
          </div>
          <el-form
                  style="width: 550px;"
                  :model="passForm"
                  status-icon
                  :rules="passRules"
                  ref="passForm"
                  label-width="100px"
          >
            <el-form-item label="新密码" prop="pass">
              <el-input type="password" v-model="passForm.pass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input type="password" v-model="passForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitPassForm()">保存</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </basic-container>
</template>

<script>
  import {mapState} from "vuex";
  import { detail, avatar, update, uploadImage } from "@/api/user/user";
  import { mobileRule, idCardRule, emailRule, passwordRule } from '@/util/validate'
  import { sm4Encrypt, sm4Decrypt, sm3Encrypt } from '@/util/smcrypto'

  export default {
    name: 'profile',
    components: {
    },
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入新密码"));
        } else {
          if (this.passForm.checkPass !== "") {
            this.$refs.passForm.validateField("checkPass");
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== this.passForm.pass) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      return {
        activeName: 'first',
        ruleForm: {
          id: '',
          account: '',
          name: '',
          mobile: '',
          email: '',
        },
        rules: {
          name: [
            {
              required: true,
              message: "请输入姓名",
              trigger: "blur"
            }
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { validator: mobileRule, trigger: 'blur' },
          ],
          cardNo: [
            { required: true, message: '请输入身份证号', trigger: 'blur' },
            { validator: idCardRule, trigger: 'blur' },
          ],
          email: [
            { validator: emailRule, trigger: 'blur' },
          ]
        },
        imageUrl: '',
        passForm: {
          id: '',
          password: ''
        },
        passRules: {
          pass: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { validator: validatePass, trigger: "blur" },
            ...passwordRule
          ],
          checkPass: [
            { required: true, message: '请输入确认密码', trigger: 'blur' },
            { validator: validatePass2, trigger: "blur"},
            ...passwordRule
          ]
        },
      };
    },
    created() {
      this.init()
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo
      }),
    },
    methods: {
      handleClick(tab, event) {
        console.log(tab, event);
      },
      init() {
        detail({id: this.userInfo.userId})
          .then(res => {
            let data = res.data;
            if (data.mobile) {
              data.mobile = sm4Decrypt(data.mobile);
            }
            if (data.cardNo) {
              data.cardNo = sm4Decrypt(data.cardNo);
            }
            this.ruleForm = data;
            this.passForm.id = data.id;
            return avatar(this.userInfo.userId);
          }).then(res => {
            this.imageUrl = res.data
          }).catch(() => {
            this.$message.error("获取用户信息失败");
          });
      },
      submitForm() {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            const mobile = this.ruleForm.mobile;
            const cardNo = this.ruleForm.cardNo;
            this.ruleForm.mobile = sm4Encrypt(mobile);
            this.ruleForm.cardNo = sm4Encrypt(cardNo);
            update(this.ruleForm).then(() => {
              this.ruleForm.mobile = mobile;
              this.ruleForm.cardNo = cardNo;
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            }, error => {
              console.log(error);
            });
          }
        });
      },
      beforeUpload(file) {
        const isImage = (file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/bmp');
        if (!isImage) {
          this.$message.error('上传文件只能是图片格式!');
          return false;
        }
        const isLimit = file.size / 1024 / 1024 < 5;
        if (!isLimit) {
          this.$message.error('上传文件大小不能超过5MB!');
          return false;
        }
      },
      uploadImage(data){
        const formData = new FormData()
        formData.append('file', data.file)
        uploadImage(formData).then(res => {
          data.onSuccess()
          this.imageUrl = res.data;
        }, error => {
          console.log(error);
          data.onError()
        });
      },
      submitPassForm() {
        this.$refs.passForm.validate(valid => {
          if (valid) {
            const pass = this.passForm.pass;
            this.passForm.password = sm3Encrypt(pass);
            update(this.passForm).then(() => {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            }, error => {
              console.log(error);
            });
          }
        })
      }
    }
  };
</script>

<style scoped lang="scss">
  @import "~_s/variables";
  @import "~_s/placeholders";
  ::v-deep .profile {
    @extend %fullsize;
  }
  ::v-deep .el-tabs {
    margin-left: 10px;
    margin-right: 10px;
  }
  ::v-deep .avatar-uploader {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409EFF;
    }
  }
  ::v-deep .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  ::v-deep .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
